<?php
namespace Product\Model;

use Zend\Db\TableGateway\TableGateway;

class ProductTable
{
    protected $tableGateway;

    public function __construct(TableGateway $tableGateway)
    {
        $this->tableGateway = $tableGateway;
    }
	
	public function getProduct($id)
    {
        $id  = (int) $id;
        $rowset = $this->tableGateway->select(array('id' => $id));
        $row = $rowset->current();
        if (!$row) {
            throw new \Exception("Could not find row $id");
        }
        return $row;
    }

    public function saveProduct(Product $product)
    {
        $data = array(
            //'id' => $product->id,
            'name'  => $product->name,			
			'description' => $product->description,
            'quantity'  => $product->quantity,
			'type' => $product->type,
            'pricefrequency'  => $product->pricefrequency,
			'ownedsecurableitem_id'  => $product->ownedsecurableitem_id,
			'account_id' => $product->account_id,
            'contact_id'  => $product->contact_id,
			'opportunity_id'  => $product->opportunity_id,
			'producttemplate_id'  => $product->producttemplate_id,
			'stage_customfield_id' => $product->stage_customfield_id,
            'sellprice_currencyvalue_id'  => $product->sellprice_currencyvalue_id,			
        );

        $id = (int)$product->id;
        if ($id == 0) {
            $this->tableGateway->insert($data);
        } else {
            if ($this->getProduct($id)) {
                $this->tableGateway->update($data, array('id' => $id));
            } else {
                throw new \Exception('Form id does not exist');
            }
        }
    }

    public function deleteProduct($id)
    {
        $this->tableGateway->delete(array('id' => $id));
    }
}
?>